// src/api/prize.ts
import { request } from './request'

export interface Prize {
  id: number
  activityId: number
  level: string // '一等奖' | '二等奖' | ...
  name: string
  quantity: number
  probability: number // 百分比
  image?: string
}

/* -------------------- mock state -------------------- */
let mockPrizes: Prize[] = [
  {
    id: 101,
    activityId: 1,
    level: '一等奖',
    name: 'iPhone 15',
    quantity: 1,
    probability: 5,
    image: ''
  },
  {
    id: 102,
    activityId: 1,
    level: '二等奖',
    name: '京东卡 500 元',
    quantity: 5,
    probability: 15,
    image: ''
  },
  {
    id: 103,
    activityId: 1,
    level: '三等奖',
    name: '小米手环',
    quantity: 20,
    probability: 80,
    image: ''
  },
  {
    id: 201,
    activityId: 2,
    level: '一等奖',
    name: '电影票兑换码',
    quantity: 50,
    probability: 100,
    image: ''
  }
]

let nextPrizeId = 1000

/* -------------------- API -------------------- */

export async function getPrizeList(): Promise<Prize[]> {
  const snapshot = JSON.parse(JSON.stringify(mockPrizes)) as Prize[]
  return request<Prize[]>({ url: '/prizes/list', method: 'GET' }, snapshot)
}

export async function getPrizesByActivity(activityId: number): Promise<Prize[]> {
  const list = mockPrizes.filter(p => p.activityId === activityId)
  const snapshot = JSON.parse(JSON.stringify(list)) as Prize[]
  return request<Prize[]>({ url: `/prizes/list?activityId=${activityId}`, method: 'GET' }, snapshot)
}

export async function addPrize(prize: Omit<Prize, 'id'>): Promise<Prize> {
  const newPrize: Prize = { ...prize, id: nextPrizeId++ }
  mockPrizes.push(newPrize)
  const out = JSON.parse(JSON.stringify(newPrize)) as Prize
  return request<Prize>({ url: '/prizes/add', method: 'POST', data: out }, out)
}

export async function updatePrize(prize: Prize): Promise<Prize> {
  const idx = mockPrizes.findIndex(p => p.id === prize.id)
  if (idx !== -1) mockPrizes[idx] = { ...prize }
  const out = JSON.parse(JSON.stringify(prize)) as Prize
  return request<Prize>({ url: '/prizes/update', method: 'PUT', data: out }, out)
}

export async function deletePrize(id: number): Promise<boolean> {
  mockPrizes = mockPrizes.filter(p => p.id !== id)
  return request<boolean>({ url: `/prizes/delete/${id}`, method: 'DELETE' }, true)
}

/* 仅开发时查看当前 mock（可选） */
export function __getMockPrizesForDev(): Prize[] {
  return mockPrizes
}
